from sqlalchemy import create_engine
from sqlalchemy import inspect

import logging as log
import os


def get_conneaction(db_config):
    log.info(db_config)
    """
    获取数据库连接
    :param db_config: 数据库配置信息
    :return: 数据库连接
    """
    connection_string = f"mysql+pymysql://{db_config['user']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/{db_config['dbname']}"
    # 创建DBTool实例
    engine = create_engine(connection_string)
    return engine


if __name__ == "__main__":
    db_config = {
        'host': '101.132.104.253',
        'port': 24370,
        'user': 'root',
        'password': 'shwqkcuyasod12',
        'dbname': 'bitforge'
    }
    connection_string = f"mysql+pymysql://{db_config['user']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/{db_config['dbname']}"
    # 创建DBTool实例
    engine = create_engine(connection_string)
    print(engine)
    # 获取当前脚本所在的目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # 构建init.sql文件的路径
    sql_path = os.path.join(current_dir, 'ai.sql')

    try:
        # 打开并读取init.sql文件的内容
        with open(sql_path, 'r', encoding='utf-8') as file:
            sql_content = file.read()

        # 分割SQL语句
        sql_statements = sql_content.split(';')

        # 执行每个SQL语句
        with engine.connect() as connection:
            for statement in sql_statements:
                if statement.strip():
                    connection.execute(statement)
        print("表创建成功！")
    except Exception as e:
        print(f"执行SQL脚本时出错: {e}")
